package com.cloudwise.plugin;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/10/21 11:32
 * @description：自建分页插件
 * @modified By：
 * @version: 1.0
 */
@Intercepts(@Signature(type = StatementHandler.class,method = "prepare",args = {Connection.class, Integer.class}))
public class PagePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //方法执行前进行增强处理，sql语句拼接上分页语句  limit  0,5
        StatementHandler sh = (StatementHandler) invocation.getTarget();
        //获取包装对象
        MetaObject metaObject = SystemMetaObject.forObject(sh);
        String sql = metaObject.getValue("delegate.boundSql.sql").toString();
        System.out.println("原始的sql语句："+sql);
        sql+=" limit 0,5 ";
        System.out.println("增强之后的sql语句："+sql);
        metaObject.setValue("delegate.boundSql.sql",sql);
        Object proceed = invocation.proceed();
        System.out.println("结束分页插件");
        return proceed;
    }
}
